package com.pine.common.redis.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.pine.common.redis.cache.RedisCache;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.spring.cache.RedissonSpringCacheManager;
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 缓存配置
 *
 * @author pine manage
 * @since 2024-08-13
 */
@Configuration
public class CacheConfig {

    @Bean(name = "redissonCacheManager")
    @ConditionalOnMissingBean
    public CacheManager redissonCacheManager(@Autowired RedissonClient redissonClient) {
        // 可以自定义缓存配置
        return new RedissonSpringCacheManager(redissonClient);
    }

    @Bean
    @ConditionalOnMissingBean
    public RedisCache redisCache() {
        return new RedisCache();
    }

    @Bean
    public RedissonAutoConfigurationCustomizer redissonAutoConfigurationCustomizer() {
        // 增加支持序列化java8的时间
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        JsonJacksonCodec jsonJacksonCodec = new JsonJacksonCodec(objectMapper);
        return config -> config.setCodec(jsonJacksonCodec);
    }
}
